package jam.network.message;

import jam.Base64;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;

import jam.model.ClientModel;
import jam.model.ServerModel;
import jam.network.ClientController;
import jam.network.NetworkController;

public class ClientActionUploadAvatar extends ClientCommand {
	protected static final String KEYWORD = "CA_AVATAR";
	protected static final int MAXIMUM_UPLOAD_SIZE = 1024*256; // in bytes
	private String imageData;
		
	@Override
	public void process(ClientController controller) {
		NetworkController network = controller.getNetworkController();
        ClientModel client = controller.getModel();
        ServerModel server = network.getModel();
        
        // Make a temp file to poot to.
        File temp;
        try {
        	temp = File.createTempFile("jam-avatar", ".img");
            OutputStream tempOut = new Base64.OutputStream(new FileOutputStream(temp), Base64.DECODE);  
        	BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOut));
        	tempWriter.write(imageData.toCharArray());
        	tempWriter.flush();
        } catch (IOException e) {
        	// OH NO
        	controller.send(new ServerResponse(this, false));
        	return;
        }         
        
        // Check if it's within the size limit
        if (temp.length() > MAXIMUM_UPLOAD_SIZE) {
        	controller.send(new ServerResponse(this, false));
        	return;
        }
        
        // We should probably 100% check that the file is an image here but
        // we just have to hope that the client can handle it instead.
        
        // Move it to some known place.
        try {
        	String newPath = String.format("data/%s", client.getUser().getUsername());
			FileUtils.copyFile(temp, new File(newPath), false);
		} catch (IOException e) {
			// something terrible occurred
			controller.send(new ServerResponse(this, false));
			return;
		}
        
		// All went well.
		controller.send(new ServerResponse(this, true));
	}

	@Override
	protected String getKeyword() {
		return ClientActionUploadAvatar.KEYWORD;
	}
	
	public ClientActionUploadAvatar(int transactionId, Scanner args) {
		super(transactionId);
		this.imageData = args.next();
	}
}
